<template>
  <div class="image-upload-tools">
    <div class="tools">
      <label for="uploads">选择</label>
      <input type="file" id="uploads" class="uploads" :value="imgFile" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 1)">
      <span @click="changeScale(1)">放大</span>
      <span @click="changeScale(-1)">缩小</span>
      <span @click="rotateLeft">左转</span>
      <span @click="rotateRight">右转</span>
      <span @click="down('blob')">下载</span>
      <span @click="finish('blob')">上传</span>
    </div>
    <div class="cropper-container">
      <div class="cropper" :style="{'width':cropperWidth+'px','height':cropperHeight+'px'}">
        <vueCropper
          ref="cropper"
          :img="option.img"
          :outputSize="option.size"
          :outputType="option.outputType"
          :info="true"
          :full="option.full"
          :canMove="option.canMove"
          :canMoveBox="option.canMoveBox"
          :original="option.original"
          :autoCrop="option.autoCrop"
          :autoCropWidth="option.autoCropWidth"
          :autoCropHeight="option.autoCropHeight"
          :fixedBox="option.fixedBox"
          @realTime="realTime"
          @imgLoad="imgLoad">
        </vueCropper>
      </div>
      <div class="show-preview" :style="{'width': option.autoCropWidth+'px'}">
        <div :style="previews.div" class="preview">
          <img :src="previews.url" :style="previews.img">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
export default {
  data() {
      return {
        headImg:'',
        //剪切图片上传
        crap: false,
        previews: {},
        option: {
          img: '',
          outputSize:1, //剪切后的图片质量（0.1-1）默认1
          full: false,//输出原图是否缩放 默认false
          outputType: 'png',//输出图片格式,png jpeg gif jpg (默认jpeg)
          canMove: true, // 是否可以拖动图片 默认true
          original: false, //上传图片按照原始比例显示 默认false
          canMoveBox: true, // 是否可以拖动截图框 默认true
          autoCrop: true, // 是否自成截图框 默认false
          autoCropWidth: 150, //截图框宽 默认为0
          autoCropHeight: 150, //截图框高 默认为0
          fixedBox: true // 是否禁止改变截图框大小 默认false
        }, 
        fileName:'',  //本机文件地址
        downImg: '#',
        imgFile:'',
        uploadImgRelaPath:'', //上传后的图片的地址（不带服务器域名）
      }
    },
    props:{
      cropperWidth:{//cropper wdith
        type: Number,
        default: 300
      },
      cropperHeight:{//cropper height
        type: Number,
        default: 300
      }
    },
    components: { 
      VueCropper 
    }, 
    methods: { 
       //放大/缩小
      changeScale(num) { 
        num = num || 1; 
        this.$refs.cropper.changeScale(num); 
      }, 
      //坐旋转
      rotateLeft() {
        this.$refs.cropper.rotateLeft(); 
      }, 
      //右旋转
      rotateRight() { 
        this.$refs.cropper.rotateRight(); 
      }, 
      //上传图片（点击上传按钮）
      finish(type) {
      //  let _this = this;
       // let formData = new FormData();
        // 输出 
        if (type === 'blob') { 
          this.$refs.cropper.getCropBlob((data) => { 
            let img = window.URL.createObjectURL(data) 
            this.model = true; 
            this.modelSrc = img; 
     //       formData.append("file", data, this.fileName);
            this.$emit("ImgUploadSubmit", data);//传数据父级提交
            /* this.$http.post("#", formData, {contentType: false, processData: false, headers:{'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
              var res = response.data;
              if(res.success == 1){
                $('#btn1').val('');
                _this.imgFile = '';
                _this.headImg = res.realPathList[0];  //完整路径
                _this.uploadImgRelaPath = res.relaPathList[0];  //非完整路径
                _this.$message({　　//element-ui的消息Message消息提示组件
                  type: 'success',
                  message: '上传成功'
                });
              }
            }) */
          }) 
        } else { 
          this.$refs.cropper.getCropData((data) => { 
            this.model = true; 
            this.modelSrc = data; 
          }) 
        } 
      }, 
      // 实时预览函数 
      realTime(data) {
        this.previews = data 
      }, 
      //下载图片
      down(type) {
        var aLink = document.createElement('a') 
        aLink.download = 'author-img' 
        if (type === 'blob') { 
          this.$refs.cropper.getCropBlob((data) => { 
            this.downImg = window.URL.createObjectURL(data)
            aLink.href = window.URL.createObjectURL(data) 
            aLink.click() 
          }) 
        } else { 
          this.$refs.cropper.getCropData((data) => { 
            this.downImg = data;
            aLink.href = data; 
            aLink.click() 
          }) 
        } 
      }, 
      //选择本地图片
      uploadImg(e, num){ 
        var _this = this;
        //上传图片 
        var file = e.target.files[0] 
        _this.fileName = file.name;
        if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) { 
          alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种') 
          return false 
        } 
		    var reader = new FileReader(); 
        reader.onload =(e) => {
          let data; 
          if (typeof e.target.result === 'object') { 
            // 把Array Buffer转化为blob 如果是base64不需要 
            data = window.URL.createObjectURL(new Blob([e.target.result])) 
          } 
          else { 
            data = e.target.result 
          }
          if (num === 1) { 
            _this.option.img = data 
          } else if (num === 2) { 
            _this.example2.img = data 
          } 
        } 
        // 转化为base64 
         reader.readAsDataURL(file) 
        // 转化为blob 
     //   reader.readAsArrayBuffer(file);
        
      }, 
      //图片加载成功回调
      imgLoad(msg){
       //msg:'success' or 'error'
      }
    }
}
</script>

<style lang="scss" scoped>
 .image-upload-tools{
   .tools{
     
     label,
     span{
       font-size:12px;
       display:inline-block;
       border:1px solid #dcdddd;
       padding:2px 5px;
       border-radius:3px;
       margin:5px 2px;
       cursor:pointer;
     }
     .uploads{
        position:absolute;
        clip:rect(0 0 0 0);
      }
   }
   .cropper-container{
    display: flex;
    display: -webkit-flex;
    justify-content: flex-start;
    -webkit-justify-content: flex-start;
    .show-preview{
      overflow: hidden;
      margin: 5px;
      .preview{
        overflow: hidden;
        border-radius: 50%;
        border: 1px solid #ccc;
        background: #ccc;
      }
    }
   }
  
 }
</style>